// pages/tools/work-strategy/work-strategy.js
const util = require("../../../utils/util");
var QQMapWX = require('../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});
let page = 1;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    state:1,
    citycode: "sz", // 城市代码
    workName: "", // 办事项目名称，默认身份证
    infoIndex: 0, // 办事指南、材料清单索引
    workType: [], // 办事子项目列表
    workTypeIndex: 0, // workType索引
    processIndex: 0, // 办理流程tabBar索引
    guide: {
      condition: {
        show: false,
        showAll: true
      },
      process: {
        show: false,
        showAll: true
      },
      timeCost: {
        show: false,
        showAll: true
      },
      local: {
        show: false,
        showAll: true
      },
      question: {
        show: false,
        showAll: true
      }
    }, // 办事指南列表折叠控制
    info: {
      condition: {},
      process: [],
      timeCost: {},
      questions: []
    },
    webInfo: [], // 网点信息
    materialList: {}, // 清单列表,
    citylist: [],
    cityIndex: 0,
    keywords: "", // 网点查询关键字
    mainWd: "", // 总网点类型名称
    cityname: "深圳市", // 网点查询使用的城市名称
    selectable: true,
    num: "", // 数据长度限制，通过options接受，传递给接口
    links: [], // 链接列表
    materialIndex: 0, // 材料清单索引
    showDetail: false,
    uselessList: ["办理流程篇幅太长，记不住", "办理条件用词太专业，看不懂", "办理地点有问题", "常见问答没有回答我的问题", "以上都不是"],
    feedbackInfo: {},
    showHalfDialog: false,
    buttons: [{
        type: 'default',
        className: '',
        text: '取消',
        value: 0
      },
      {
        type: 'primary',
        className: '',
        text: '确认',
        value: 1
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      workName: options.name ? options.name : "身份证",
      num: options.num ? options.num : "",
      citycode: options.city || ks.getStorageSync("citycode"),
    });
    util.getUrl(app.globalData.url).then(e => {
      qqmapsdk.reverseGeocoder({
        type: 'wgs84',
        success: (res) => {
          const lat = res.result.location.lat;
          const lnt = res.result.location.lng;
          this.setData({
            lat,
            lnt,
          });
          this.getInfo();
        },
      });
    });
  },

  tapDialogButton() {
    this.setData({
      showDetail: false
    });
  },

  open() {
    this.setData({
      showHalfDialog: true
    });
  },

  /**
   * 确定没帮助
   * @method confirm
   */
  confirm() {
    let type = this.data.feedbackInfo[this.data.workTypeName];
    if (type.uselessIndex === "") {
      uni.showToast({
        title: "请选择原因",
        icon: "none"
      });
    } else {
      util.request(
        "wenti.php", {
          action: "add",
          laiyuan: `WX-${this.data.cityname}-${this.data.workName}-${this.data.workType[this.data.workTypeIndex].title}`,
          type: "没帮助",
          result: this.data.uselessList[type.uselessIndex],
          remark: type.feedbackContent,
          publictime: new Date().getTime()
        },
        "POST"
      ).then(res => {
        ks.showToast({
          title: "已收到您的反馈，感谢您的参与",
          icon: "none",
          success: () => {
            type.useless = 1;
            type.hasFeedback = true;
            this.setData({
              showHalfDialog: false,
              feedbackInfo: this.data.feedbackInfo
            });
          }
        });
      });
    }
  },
  onMaskMouseMove(){
      // nothing
  },  
  /**
   * 没帮助原因选择
   * @method feedbackChange
   * @param {Evnet} e
   */
  feedbackChange(e) {
    let index = e.detail.value
    // 选择以上都不是时，展示textarea
    if (index == 4) {
      this.data.feedbackInfo[this.data.workTypeName].showTextarea = true;
    } else {
      this.data.feedbackInfo[this.data.workTypeName].showTextarea = false;
    }
    this.data.feedbackInfo[this.data.workTypeName].uselessIndex = index;
    this.setData({
      feedbackInfo: this.data.feedbackInfo
    })
  },

  input(e) {
    this.data.feedbackInfo[this.data.workTypeName].feedbackContent = e.detail.value;
    this.setData({
      feedbackInfo: this.data.feedbackInfo
    });
  },

  /**
   * 取消没帮助
   * @method cancel
   */
  cancel() {
    this.setData({
      showHalfDialog: false
    });
  },

  /**
   * 有帮助/没帮助按钮切换事件
   * @method feedback
   * @param {string} type 按钮类型
   */
  feedback(e) {
    let type = util.getValue('type', e);
    let feedType = this.data.feedbackInfo[this.data.workTypeName];
    if (feedType.hasFeedback) {
      ks.showToast({
        title: "请不要重复提交",
        icon: "none"
      });
    } else {
      if (type === "usefull") {
        feedType.usefull = ~feedType.usefull + 2;
        this.setData({
          feedbackInfo: this.data.feedbackInfo
        });
        // 第一次选择有帮助时，发送请求
        if (feedType.firstUsefull) {
          util.request(
            "wenti.php", {
              action: "add",
              laiyuan: `WX-${this.data.cityname}-${this.data.workName}-${this.data.workType[this.data.workTypeIndex].title}`,
              type: "有帮助",
              result: "",
              remark: "",
              publictime: new Date().getTime()
            },
            "POST"
          ).then(res => {
            feedType.firstUsefull = false
            this.setData({
              feedbackInfo: this.data.feedbackInfo
            });
          });
        }
      } else if (type === "useless") {
        feedType.usefull = 0;
        this.open();
        this.setData({
          feedbackInfo: this.data.feedbackInfo
        });
      }
    }
  },

  /**
   * 获取信息
   * @method getInfo
   */
  getInfo(obj) {
    util.request("banshi.php", {
        // citycode: this.citycode,
        citycode: this.data.citycode,
        name: this.data.workName,
        num: this.data.num,
        time: new Date().getTime()
      }, "GET")
      .then(res => {
        let state = res.data.state
        this.setData({
          state
        })
        if (res.data.state === 1) {
          this.setData({
            cityId: res.data.data.cityid
          });
          if (res.data.data.citylist) {
            let citylist = [];
            for (let key in res.data.data.citylist) {
              citylist.push({
                cityid: key,
                cityname: res.data.data.citylist[key]
              });
            }
            this.data.cityIndex = citylist.findIndex(city => city.cityid === this.data.citycode);
            this.setData({
              citylist,
              cityIndex: this.data.cityIndex
            });
          }
          if (res.data.data.city) {
            this.setData({
              cityname: res.data.data.city,
              address: ["", this.cityname, "全部"]
            });
          }
          this.setData({
            mianWd: res.data.data.wd,
            workType: res.data.data.subject,
            workTypeName: res.data.data.subject[this.data.workTypeIndex].title
          });
          this.data.workType.forEach(item => {
            Object.defineProperty(this.data.feedbackInfo, item.title, {
              value: {
                usefull: 0,
                useless: 0,
                feedbackContent: "", // 备注,
                hasFeedback: false, // 判断是否已经反馈
                firstUsefull: true, // 判断是否是第一次选择有帮助，重复选择只提交一次请求
                uselessIndex: "",
                showTextarea: false
              },
              enumerable: true,
              writable: true,
              configurable: true
            });
          });
          this.setData({
            feedbackInfo: this.data.feedbackInfo
          })
          // 如果当前项目网点类型与主类型一致，使用主类型请求，否则使用当前项目网点类型请求;
          if (this.data.workType[this.data.workTypeIndex].wd === res.data.data.wd) {
            this.getWebInfo(res.data.data.wd);
          } else {
            this.getWebInfo(this.data.workType[this.data.workTypeIndex].wd);
          }
          this.showData();
        } else {
          this.data.workType = [];
          this.data.materialList = [];
          Object.keys(this.data.info).forEach(item => {
            this.data.info[item].content = [];
            this.data.info[item].child = [];
          });

          this.setData({
            workType: this.data.workType,
            materialList: this.data.materialList,
            info: this.data.info,
          });
          ks.showToast({
            title: "当前城市暂无数据",
            icon: "none"
          });
        }
      })
      .catch(err => {
        // ks.showToast({
        //   title: "当前城市暂无数据",
        //   icon: "none"
        // });
      });
  },

  /**
   * 展示页面数据
   * @method showData
   */
  showData() {
    let workInfo = this.data.workType[this.data.workTypeIndex].block;
    let workType = [{
        name: "办理条件",
        key: "condition"
      },
      {
        name: "办理流程",
        key: "process"
      },
      {
        name: "办理时限与费用/办理时限及费用",
        key: "timeCost"
      },
      {
        name: "常见问答/常见问题",
        key: "questions"
      }
    ];
    workType.forEach(item => (this.data.info[item.key] = this.getGuideInfo(item.name, workInfo)));
    this.setData({
      materialList: this.getGuideInfo("办理材料", workInfo)
    });
    if (this.data.materialList.child) {
      this.data.materialList.child.forEach(item => {
        if (item.content) {
          item.content.forEach(link => {
            if (link.links.length > 0) {
              this.setData({
                links: [...this.data.links, ...link.links]
              });
            }
          });
        }
      });
    }

    if (this.data.materialList.content) {
      this.data.materialList.content.forEach(item => {
        if (item.links.length) {
          this.setData({
            links: [...this.data.links, ...item.links]
          });
        }
      });
    }
    this.setData({
      materialList: this.data.materialList
    });

    for (let type in this.data.info) {
      if (this.data.info[type].content) {
        let content = this.data.info[type].content;
        content.forEach(item => {
          if (item.links.length > 0) {
            let links = item.links;
            this.setData({
              links: [...this.data.links, ...links]
            });
          }
        });
      }

      if (type === "process") {
        if (this.data.info[type].child) {
          this.data.info[type].child.forEach(item => {
            item.content.forEach(item => {
              this.setData({
                links: [...this.data.links, ...item.links]
              });
            });
          });
        }
      }

      if (type === "questions") {
        if (this.data.info[type].child) {
          this.data.info[type].child.forEach(item => {
            if (item.content) {
              item.content.forEach(link => {
                if (link.links.length > 0) {
                  this.setData({
                    links: [...this.data.links, ...link.links]
                  });
                }
              });
            }
          });
        }
      }
      this.setData({
        info: this.data.info
      });
    }
  },

  /**
   * 获取网点信息
   * @method getWebInfo
   * @param {string} [keywords] 网点名称
   */
  getWebInfo(keywords) {
    // 当前网点类型与主类型一致，不请求数据，否则请求数据;
    if (keywords) {
      this.setData({
        keywords
      })
      let data = {
        city: this.data.cityname,
        county: "全部",
        type: 3,
        keywords,
        lat: this.data.lat,
        lnt: this.data.lnt,
        page,
        size: 5,
        action: "search"
      };
      util.request("network.php", data, "POST").then(res => {

        if (res.data.state == 1) {
          if (this.data.webInfo.length <= res.data.count) {
            res.data.data.search.forEach(item => {
              if (item.distance) {
                if (item.distance < 1) item.distance = `${(parseFloat(item.distance) * 1000).toFixed(0)}米`;
                else item.distance = `${parseFloat(item.distance).toFixed(2)}公里`;
              }
            });
            this.data.webInfo = res.data.data.search.slice(0, 2);
            this.setData({
              webInfo: this.data.webInfo
            });
          }
        }
      });
    } else {
      if (this.data.workType[this.data.workTypeIndex].wd !== this.data.mianWd) {
        this.getWebInfo(this.data.workType[this.data.workTypeIndex].wd);
      } else if (!this.data.workType[this.data.workTypeIndex].wd) {
        this.data.webInfo = [];
        this.setData({
          webInfo: this.data.webInfo
        });
      }
    }
  },

  /**
   * 获取对应列表数据（例如：办理条件、办理流程等）
   * @method getGuideInfo
   * @param {string} name 流程名称
   * @param {object} workInfo 当前项目数据
   * @return {object} 返回对应项目数据
   */
  getGuideInfo(name, workInfo) {
    return workInfo.filter(guide => name.includes(guide.title)).length ? workInfo.filter(guide => name.includes(guide.title))[0] : "";
  },

  /**
   * 顶部导航栏切换事件
   * @method changeType
   * @param {string} index 顶部导航栏索引
   * @param {string} id 子项目id
   */
  changeType(e) {
    for (let key in this.data.guide) {
      this.data.guide[key].showAll = true;
      this.data.guide[key].show = false;
    }
    this.setData({
      guide: this.data.guide
    });
    let index = util.getValue('index', e);
    this.setData({
      workTypeIndex: index,
      processIndex: 0,
      workTypeName: this.data.workType[index].title
    });
    this.showData();
    this.getWebInfo();
  },

  /**
   * 切换办事指南和材料清单
   * @method changeInfoIndex
   * @param {string} index 办事指南和材料清单索引
   */
  changeInfoIndex(e) {
    let index = util.getValue('index', e);
    this.setData({
      infoIndex: index
    });
  },

  /**
   * 展开办事指南列表详细信息
   * @method showDetail
   * @param {string} type 办事指南名称
   */
  showDetail(e) {
    let type = util.getValue('type', e);
    this.data.guide[type].show = !this.data.guide[type].show;
    this.setData({
      guide: this.data.guide
    });
  },

  /**
   * 切换网上办理、现场办理
   * @method changeProcessIndex
   * @param {string} index 网上办理、现场办理索引
   */
  changeProcessIndex(e) {
    let index = util.getValue('index', e);
    this.setData({
      processIndex: index
    });
  },

  /**
   * 展示全部信息
   * @method showAll
   * @par1am {string} type 办事指南名称
   */
  showAll(e) {
    let type = util.getValue('type', e);
    this.data.guide[type].showAll = false;
    this.setData({
      guide: this.data.guide
    });
  },

  /**
   * 城市选择pciker
   * @method pickCity
   */
  pickCity(e) {
    this.data.cityIndex = e.detail.value;
    this.data.citycode = this.data.citylist[e.detail.value].cityid;
    this.setData({
      cityIndex: this.data.cityIndex,
      citycode: this.data.citycode
    });
    let eindex = e
    this.getInfo(eindex);
  },

  /**
   * 查看网点详情
   * @method toWebDetail
   * @param {string} index 网点索引
   */
  toWebDetail(e) {
    let index = util.getValue('index', e);
    ks.navigateTo({
      url: `/pages/tools/wangdian/detail/detail?detailId=${this.data.webInfo[index].id}`
    });
  },

  /**
   * 隐藏问答内容
   * @method showQuestionContent
   * @param {striong} index 问答索引
   * @tips 暂时不做此功能
   */
  /* showQuestionContent(index) {
  	this.questions[index].ellipsis = false;
  }, */

  /**
   * 展示材料清单详情
   * @method showMaterialDetail
   * @param {string} index 材料清单索引
   */
  showMaterialDetail(e) {
    let index = util.getValue('index', e);
    this.setData({
      materialIndex: index,
      showDetail: true
    });
  },

  /**
   * 预览图片
   * @method previewImage
   * @param {string} src 图片链接
   */
  previewImage(e) {
    let src = util.getValue('src', e);
    ks.previewImage({
      current: src,
      urls: [src]
    });
  },

  /**
   * 展示全部网点信息
   * @method showAllWebInfo
   * @param {string} keywords 网点名称
   */
  showAllWebInfo(e) {
    let keywords = util.getValue('keywords', e);
    ks.navigateTo({
      url: `/pages/tools/wangdian/select/select?keywords=${keywords}&type=1&provinceName=默认&cityName=${this.data.cityname}&districtName=全部&cityCode=${this.data.citycode}`
    });
  },

  /**
   * 文章内连接点击事件
   * @method htmlLink
   * @param {Object} res 组件返回对象
   */
  linkTap(res) {
    let url = res.detail.href;
    let linkInfo = this.data.links.filter(link => link.url === url);
    linkInfo.length && linkInfo[0].id ? ks.navigateTo({
      url: `/pages/article/detail/detail?id=${linkInfo[0].id}&city=${linkInfo[0].city}&type=${linkInfo[0].type}`
    }) : util.navContact(url, url);

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: `本地宝-${this.data.cityname}-${this.data.workName}-办事`,
      path: `/pages/tools/work-strategy/work-strategy?name=${this.data.workName}&num=${this.data.num}&citycode=${this.data.citycode}`
    }
  }
})